import os
import argparse
import json
from comtypes import client
# 解决print 中文乱码问题
import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# 获取命令行参数
parser = argparse.ArgumentParser()
# 文件数组
parser.add_argument('-filePath', type=str, default='[]', help='argument 1')
# 目录配置信息
parser.add_argument('-outputManage', type=str, default='{}', help='argument 2')

args = parser.parse_args()


def ppt_pdf(path, outputManage):
  # 获取路径配置信息、文件列表
  equalSource = json.loads(outputManage)['equalSource']
  outputPath = json.loads(outputManage)['outputPath']
  filePaths = json.loads(path)

  # 遍历文件路径数组
  for file in filePaths:

    # 过滤临时文件
    if '~$' in file['fileName']:
      continue

    # 过滤非pdf格式文件
    # if file['fileName'].split('.')[-1] != 'pdf':
    #     continue
    # 获取文件名称
    # file_name = file.split('.')[0]
    file_name = os.path.splitext(file['fileName'])[0]

    # pdf文件名称
    # pdf_name = os.getcwd() + '\\' + file
    pdf_name = file['filePath']

    # pdf 源文件目录
    pdf_parent_path = os.path.dirname(file['filePath'])
    docx_name = ''
    # 当equalSource为false时，转换的doc文件统一放在配置的目录中
    if equalSource == False:
      # docx文件名称，equalSource为false时
      docx_name = outputPath + '\\' + file_name + '.pdf'
    else:
      # docx文件保存在源文件目录下
      docx_name = pdf_parent_path + '\\' + file_name + '.pdf'
    
    # 调用office软件转换 
    powerpoint = client.CreateObject("Powerpoint.Application")
    # ppt 不能隐藏，只能是转换完毕后 Quit 退出
    powerpoint.Visible = True
    try:
      slides = powerpoint.Presentations.Open(file['filePath'])
      slides.SaveAs(docx_name, FileFormat=32)
      slides.Close()
      print(file['fileId'])
    except:
      print([])
    finally:
      powerpoint.Quit()

if __name__ == '__main__':
  ppt_pdf(args.filePath, args.outputManage)
